import { Layout } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { Navigate, useLocation } from "react-router-dom";
import { RootState } from "@/store";

import BasicLayoutSider from "./components/BasicLayoutSider";
import BasicLayoutHeader from "./components/BasicLayoutHeader";
import BasicLayoutContent from "./components/BasicLayoutContent";

import "./BasicLayout.css";
import { checkPermission } from "@/utils";
import { useEffect } from "react";
import { setMenuItems } from "@/store/modules/user";

const BasicLayout = () => {
  const location = useLocation();
  const dispatch = useDispatch();
  // 取出 仓库中的 当前用户 左侧菜单数据
  const menuItems = useSelector((state: RootState) => state.user.menuItems);
  // 取出 仓库中的 token
  const token = useSelector((state: RootState) => state.user.token);
  const hasPermission = checkPermission(menuItems, location.pathname);

  useEffect(() => {
    dispatch(setMenuItems());
  }, []);
  // 判断 token 是否存在
  if (token) {
    // 再判断是否有访问这个页面的权限，使用 location.pathname 是否存在于当前用户的 menuItems 中
    // console.log("hasPermission", hasPermission);
    if (hasPermission) {
      return (
        <Layout id="basic-layout">
          {/* 左侧菜单 */}
          <BasicLayoutSider />

          <Layout className="site-layout">
            {/* 右侧头部 */}
            <BasicLayoutHeader />

            {/* 右侧内容 */}
            <BasicLayoutContent />
          </Layout>
        </Layout>
      );
    } else {
      // 403 页面
      return <div>没有权限</div>;
    }
  } else {
    // 没有登录的
    return (
      <Navigate
        to={{
          pathname: "/login",
          search: `?redirect=${location.pathname + location.search}`,
        }}
      />
    );
  }
};

export default BasicLayout;
